/**
 * Copyright (c) 2019, ShangHai YTO Co., Ltd.
 * All right reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF YTO
 * CO., LTD.  THE CONTENTS OF THIS FILE MAY NOT BE DISCLOSED
 * TO THIRD PARTIES, COPIED OR DUPLICATED IN ANY FORM, IN WHOLE OR IN PART,
 * WITHOUT THE PRIOR WRITTEN PERMISSION OF YTO
 * CO., LTD.
 */
package org.sc.xl.guavatest;

import com.google.common.util.concurrent.RateLimiter;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: TODO 请在此添加描述
 * @reason: TODO ADD REASON(可选)
 * @author FXL
 *
 * @date 2023/10/24 10:11 
 * @since JDK 1.8
 */
public class GuavaTest {


    public static void main(String[] args) throws InterruptedException {

        ReentrantLock lock = new ReentrantLock();

        RateLimiter limiter = RateLimiter.create(10);

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 50; i++) {
            executorService.submit(new Task(limiter, lock));
        }
        executorService.shutdown();
    }


    static class Task implements Runnable {

        private RateLimiter rateLimiter;

        private ReentrantLock reentrantLock;


        public Task(RateLimiter rateLimiter, ReentrantLock reentrantLock) {
            this.rateLimiter = rateLimiter;
            this.reentrantLock = reentrantLock;
        }

        @Override
        public void run() {

            int randInt = 1;
            reentrantLock.lock();
            try {
                randInt = new Random().nextInt(10) + 1;
            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                reentrantLock.unlock();
            }
            System.err.println(Thread.currentThread().getName() + "  --  " + String.format("%5f", rateLimiter.acquire(randInt)) + "  --  " + " 调用模拟请求数:" + randInt);
        }
    }
}